﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Xml;
using MyAlbum.Services;
using System.Web.Mvc;

namespace PersonalAlbum
{
    public class RssFormatter
    {
        public static string GetRssFeed(UrlHelper url)
        {
            var iconfig = ObjectFactory.GetInstance<IConfiguration>();
            StringWriter sw = new StringWriter();
            XmlTextWriter writer = new XmlTextWriter(sw);
            writer.Indentation = 4;
            writer.Formatting = Formatting.Indented;

            writer.WriteStartElement("rss");
            writer.WriteAttributeString("version", "2.0");
            writer.WriteAttributeString("xmlns:atom", "http://www.w3.org/2005/Atom");
            writer.WriteStartElement("channel");

            writer.WriteStartElement("atom:link");
            writer.WriteAttributeString("href", ConfigManager.SiteUrl + "/RSS" + (iconfig.UseAspxExtensions ? ".aspx" : null));
            writer.WriteAttributeString("rel","self");
            writer.WriteAttributeString("type","application/rss+xml");
            writer.WriteEndElement();
            writer.WriteElementString("title", iconfig.SiteTitle);
            writer.WriteElementString("description","");
            writer.WriteElementString("link", ConfigManager.SiteUrl);
            writer.WriteElementString("ttl", "180");

            var entries = ObjectFactory.GetInstance<IEntryService>().GetLastItems(50);
            foreach (var item in entries.OrderBy(e => e.Date).Reverse())
            {
                writer.WriteStartElement("item");
                writer.WriteStartElement("title");
                writer.WriteCData(item.Title);
                writer.WriteEndElement();//title
                string link = ConfigManager.SiteUrl + url.Action("Details", "Entry", new { id = item.Id });
                writer.WriteElementString("link",link);
                writer.WriteStartElement("guid");
                writer.WriteAttributeString("isPermaLink", "true");
                writer.WriteString(link);
                writer.WriteEndElement();//guid
                writer.WriteStartElement("description");
                writer.WriteCData(item.Description + "<br/>" + item.Render());
                writer.WriteEndElement();//description
                //writer.WriteElementString("author","");
                writer.WriteElementString("pubDate",item.Date.ToString("r"));
                //writer.WriteElementString("pubGMTDate", item.Date.ToString("r"));
                writer.WriteEndElement();//item
            }

            writer.WriteEndElement();//channel

            writer.WriteEndElement();//rss

            writer.Close();

            //   writer.WriteProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"RssArticles.xslt\" version=\"1.0\"");
            return sw.ToString();

        }
    }
}
